package com.alibaba.citrus.ots.platform.enhance.facade.service;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.platform.enhance.functions.constants.StrategyConstants;
import com.alibaba.citrus.ots.platform.enhance.repository.StrategyQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIds2Request;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIds2Response;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.api.strategyquery.dto.QueryGenerateOrderSwitchRequest;
import com.epoch.app.otsplatformenhance.api.strategyquery.service.StrategyQueryService;
import com.epoch.app.otsplatformenhance.enums.DimensionTypeEnum;
import com.epoch.app.otsplatformenhance.enums.StrategyTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.*;
import com.epoch.app.otsplatformenhance.model.enums.StatusEnum;
import com.epoch.app.otsplatformenhance.sdo.DimensionSDO;
import com.epoch.app.otsplatformenhance.sdo.StrategySDO;
import com.epoch.app.otsplatformenhance.strategy.dto.QueryValidStrategyListRequest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Primary
public class StrategyQueryServiceImpl implements StrategyQueryService {

    @Resource
    private StrategyQueryRepository strategyQueryRepository;

    @Resource
    private BaseDataService baseDataService;

    @Override
    @FacadeInvoker
    public Result<List<StrategyPageQueryResponse>> pageQuery(StrategyPageQueryRequest request) {
        //查询的组织外部编码转换组织ID   换下拉框
//        BaselineGetOrganizationByOutCodes2Request orgQueryReq = new BaselineGetOrganizationByOutCodes2Request();
//        orgQueryReq.setOutCodes(Lists.newArrayList(request.getOrganizationCode()));
//        BaselineGetOrganizationByOutCodes2Response response = baseDataService.baselineGetOrganizationByOutCodes2(orgQueryReq);
//        if(CollectionUtils.isNotEmpty(response.getResult())){
//            request.setOrganizationCode(response.getResult().get(0).getId());
//        }

        Result<List<StrategyPageQueryResponse>> listResult = strategyQueryRepository.pageQuery(request);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return Result.listSuccess(null,0);
        }

        //查询策略列表中的组织id转换组织外部编码
        List<String> orgIds = listResult.getResult().stream().map(x -> {
            return x.getOrganizationCode();
        }).collect(Collectors.toList());
        BaselineGetOrganizationByIds2Request orgQueryReqById = new BaselineGetOrganizationByIds2Request();
        orgQueryReqById.setIds(orgIds);
        if (!StrategyTypeEnum.INVENTORY_ROUTING.getCode().equals(request.getType())) {
            BaselineGetOrganizationByIds2Response getOrgsResponse = baseDataService.baselineGetOrganizationByIds2(orgQueryReqById);
            Map<String, OrganizationSDO> orgsMap = Nullable.stream(getOrgsResponse.getResult()).collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(), (v1, v2) -> v1));
            listResult.getResult().forEach(x -> {
                OrganizationSDO org = orgsMap.get(x.getOrganizationCode());
                x.setOrgOutCode(org.getOutCode());
                x.setOrganizationName(org.getName());
            });
        }
        return Result.listSuccess(listResult.getResult(),listResult.getTotal());
    }

    @Override
    @FacadeInvoker
    public Result<StrategyQueryByIdResponse> queryById(StrategyQueryByIdRequest request) {
        if (StringUtils.isEmpty(request.getId())) {
            StrategyQueryByIdResponse response = new StrategyQueryByIdResponse();
            StrategySDO strategySDO = new StrategySDO();
            strategySDO.setDimensionType(DimensionTypeEnum.DEPARTMENT.getCode());
            response.setStrategySDO(strategySDO);
            return Result.success(response);
        }
        Result<StrategyQueryByIdResponse> response = strategyQueryRepository.queryById(request);
        return response;
    }
    @Override
    public Result<DailyStrategyDetailResponse> queryInventoryRouting(StrategyQueryByIdRequest request) {
        DailyStrategyDetailResponse resp=new DailyStrategyDetailResponse();
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setDimensionType(DimensionTypeEnum.DEPARTMENT.getCode());
        Result<StrategyQueryByIdResponse> response = strategyQueryRepository.queryById(request);
        if (response == null || response.getResult() == null) {
            return Result.success(resp);
        }
        strategySDO = response.getResult().getStrategySDO();
        if (MapUtils.isNotEmpty(strategySDO.getFeature())) {
            String inventoryrouting = strategySDO.getFeature().get(StrategyConstants.INVENTORY_ROUTING);
            InventoryRoutingFeatureSDO inventoryroutingNew = JSONObject.parseObject(inventoryrouting, InventoryRoutingFeatureSDO.class);
            resp.setInventoryRoutingFeature(inventoryroutingNew);
            String calculatepriority = strategySDO.getFeature().get(StrategyConstants.CALCULATE_PRIORITY);
            List<CalculatePriority> calculatePriorities = JSONObject.parseArray(calculatepriority, CalculatePriority.class);
            resp.setCalculatePriority(calculatePriorities);
        }
        //根据维度类型区分不同的结果
        List<DimensionSDO> scItemList = new ArrayList<>();
        List<DimensionSDO> wareHouseList = new ArrayList<>();
        List<DimensionSDO> dimensionList = new ArrayList<>();
        List<DimensionSDO> departmentList = new ArrayList<>();
        List<DimensionSDO> groupProductList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(strategySDO.getDimensionSDOList())){
            strategySDO.getDimensionSDOList().forEach(dimensionSDO -> {
                if (DimensionTypeEnum.STORE_ROOM.getCode().equals(dimensionSDO.getCode())){
                    wareHouseList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.GOODS.getCode().equals(dimensionSDO.getCode())){
                    scItemList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.SALESMAN.getCode().equals(dimensionSDO.getCode())){
                    dimensionList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.CHANNEL.getCode().equals(dimensionSDO.getCode())){
                    dimensionList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.DEPARTMENT.getCode().equals(dimensionSDO.getCode())){
                    departmentList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.GROUPPRODUCT.getCode().equals(dimensionSDO.getCode())){
                    groupProductList.add(dimensionSDO);
                }
            });
        }
        BeanUtils.copyProperties(strategySDO,resp);
        resp.setScItemList(scItemList);
        resp.setWareHouseList(wareHouseList);
        resp.setDimensionList(dimensionList);
        resp.setDepartmentList(departmentList);
        resp.setGroupProductList(groupProductList);
        return Result.success(resp);
    }
    @Override
    @FacadeInvoker
    public Result<DailyStrategyDetailResponse> queryDailyStrategy(StrategyQueryByIdRequest request) {
        DailyStrategyDetailResponse resp = new DailyStrategyDetailResponse();
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setDimensionType(DimensionTypeEnum.DEPARTMENT.getCode());
//        resp.setStrategySDO(strategySDO);
        Result<StrategyQueryByIdResponse> response = strategyQueryRepository.queryById(request);
        if (response == null || response.getResult() == null) {
            return Result.success(resp);
        }
        strategySDO = response.getResult().getStrategySDO();
        //根据维度类型区分不同的结果
        List<DimensionSDO> scItemList = new ArrayList<>();
        List<DimensionSDO> wareHouseList = new ArrayList<>();
        List<DimensionSDO> dimensionList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(strategySDO.getDimensionSDOList())){
            strategySDO.getDimensionSDOList().forEach(dimensionSDO -> {
                if (DimensionTypeEnum.STORE_ROOM.getCode().equals(dimensionSDO.getCode())){
                    wareHouseList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.GOODS.getCode().equals(dimensionSDO.getCode())){
                    scItemList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.SALESMAN.getCode().equals(dimensionSDO.getCode())){
                    dimensionList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.CHANNEL.getCode().equals(dimensionSDO.getCode())){
                    dimensionList.add(dimensionSDO);
                }
                if (DimensionTypeEnum.DEPARTMENT.getCode().equals(dimensionSDO.getCode())){
                    dimensionList.add(dimensionSDO);
                }
            });
        }
        BeanUtils.copyProperties(strategySDO,resp);
        resp.setScItemList(scItemList);
        resp.setWareHouseList(wareHouseList);
        resp.setDimensionList(dimensionList);
        return Result.success(resp);
    }

    @Override
    @FacadeInvoker
    public Result<MoreConditionQueryResponse> moreConditionQuery(MoreConditionQueryRequest request) {
        Map<String, String> codeAndValue = new HashMap<>();
        if (!StringUtils.isEmpty(request.getDepartmentCode())) {
            codeAndValue.put(DimensionTypeEnum.DEPARTMENT.getCode(), request.getDepartmentCode());
        }
        if (!StringUtils.isEmpty(request.getChannelCode())) {
            codeAndValue.put(DimensionTypeEnum.CHANNEL.getCode(), request.getChannelCode());
        }
        if (!StringUtils.isEmpty(request.getCustomerCode())) {
            codeAndValue.put(DimensionTypeEnum.CUSTOMER.getCode(), request.getCustomerCode());
        }
        if (!StringUtils.isEmpty(request.getWareHouseCode())) {
            codeAndValue.put(DimensionTypeEnum.STORE_ROOM.getCode(), request.getWareHouseCode());
        }
        Result<MoreConditionQueryResponse> moreConditionQueryResponseResult = strategyQueryRepository.moreConditionQuery(request, codeAndValue);
        return moreConditionQueryResponseResult;
    }

    @Override
    @FacadeInvoker
    public Result<FbGenerateOrderSwitchReponse> queryFbConfigDetail(FbGenerateOrderSwitchRequest fbGenerateOrderSwitchRequest) {
        StrategyQueryByIdRequest request = new StrategyQueryByIdRequest();
        request.setId(fbGenerateOrderSwitchRequest.getId());
        Result<StrategyQueryByIdResponse> response = strategyQueryRepository.queryById(request);
        if (!response.isSuccess() || response.getResult() == null) {
            return Result.success(null);
        }
        StrategySDO byIdResponse = response.getResult().getStrategySDO();
        FbGenerateOrderSwitchReponse resp = new FbGenerateOrderSwitchReponse();
        resp.setOrgCode(byIdResponse.getOrganizationCode());
        resp.setStrategyName(byIdResponse.getName());

        ExecuteActionDesc desc = new ExecuteActionDesc();
//        desc.setDisabled(true);
        desc.setValue(false);
        desc.setText("关闭");
        if ("1".equals(byIdResponse.getDimensionSDOList().get(0).getRuleValue())) {
            desc.setValue(true);
            desc.setText("开启");
        }
        resp.setSwitchId(byIdResponse.getDimensionSDOList().get(0).getId().toString());
        resp.setIsGenerate(desc);
        List<String> times = new ArrayList<>();
        times.add(byIdResponse.getValidBeginTime().toLocaleString());
        times.add(byIdResponse.getValidEndTime().toLocaleString());
        resp.setValidateTime(times);
        resp.setType(byIdResponse.getType());
        resp.setId(byIdResponse.getId());
        resp.setOrgName(byIdResponse.getOrganizationName());
        return Result.success(resp);
    }

    @Override
    @FacadeInvoker
    public Result<Boolean> queryGenerateOrderSwitch(QueryGenerateOrderSwitchRequest request) {
        QueryValidStrategyListRequest repo = new QueryValidStrategyListRequest();
        repo.setOrganizationCode(request.getOrganizationCode());
        repo.setType(request.getStrategyType());
        repo.setValidTimePoint(new Date());
        repo.setStatus("1");
        List<StrategySDO> strategySDOS = strategyQueryRepository.queryValidStrategyList(repo);
        Boolean switchResult = Boolean.FALSE;
        if (CollectionUtils.isNotEmpty(strategySDOS)) {

            StrategySDO byIdResponse = strategySDOS.get(0);

            if ("1".equals(byIdResponse.getDimensionSDOList().get(0).getRuleValue())) {
                switchResult = Boolean.TRUE;
            }
        }
        return Result.success(switchResult);
    }
}
